﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMS.BLL;
using PMS.Entity;
using PMS.Resources;
using PMS.Win;
using PMS.Utils;
using DevExpress.XtraEditors.Mask;
using PMS.DanhMucChung;
using System.Collections.Generic;
using PMS.ValidationRules;
using System.Collections;
using DevExpress.XtraEditors.Popup;
using DevExpress.Utils.Win;
using PMS.ReportViewer;
namespace PMS.ChucNang
{
    public partial class BienBanKiemKeKhoEntry2 : FormEntryBase
    {
        #region Constants
        private const string BINDING_PROPERTY = "EditValue";
        private string NEW_String = Messages.GetString(Constants.NEW);
        private const string INVALID_QUANTITY = "INVALID_QUANTITY";
        #endregion

        #region Private Members
        protected BienBanKiemKeKhoBO m_Service;
        protected BaseEntityCollection<ChiTietBienBanKiemKeKho> m_DetailItemsList;
        protected ChiTietBienBanKiemKeKhoBO m_ChiTietService;
        private bool m_isDuplicateProduct;
        protected SanPhamBO m_ProductService;
        protected List<ComboItem> m_listYears;
        protected List<ComboItem> m_ListMonths;
        private List<ComboItem> m_Ketluan;

        #endregion

        #region Properties
        protected Entity.BienBanKiemKeKho CurrentBBKKEntry
        {
            get
            {
                return base.Entity as Entity.BienBanKiemKeKho;
            }
            set
            {
                base.Entity = value;
            }
        }
        #endregion

        #region Services
        public BienBanKiemKeKhoBO Service
        {
            get
            {
                if (m_Service == null)
                {
                    m_Service = new BienBanKiemKeKhoBO();
                }
                return m_Service;
            }
        }

        public ChiTietBienBanKiemKeKhoBO ChiTietService
        {
            get
            {
                if (m_ChiTietService == null)
                {
                    m_ChiTietService = new ChiTietBienBanKiemKeKhoBO();
                }
                return m_ChiTietService;
            }
        }

        public SanPhamBO ProductService
        {
            get
            {
                if (m_ProductService == null)
                {
                    m_ProductService = new SanPhamBO();
                }
                return m_ProductService;
            }
        }
        #endregion

        #region Constructors
        public BienBanKiemKeKhoEntry2(string functionID)
            : base(functionID)
        {
            InitializeComponent();
            Init();
        }
        #endregion

        #region Init Data and Style
        private void Init()
        {
            InitData();
            InitStyle();
        }

        private void InitData()
        {
            m_DetailItemsList = new BaseEntityCollection<ChiTietBienBanKiemKeKho>();
            BindingToGrid();
            //LoadDatasourceCbbNam();
            //LoadDatasourceCbbThang();
            LoadDatasourceCbbKetluan();
        }

        private void InitStyle()
        {
            //grid
            grdDetail.CausesValidation = false;
            bteMaBBKK.Tag = "Ignore";
            this.grvDetail.IndicatorWidth = Constants.INDICATOR_WIDTH;
            cbbKetLuan.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;

            this.grvDetail.OptionsView.ShowFooter = false;
            this.grvDetail.OptionsMenu.EnableFooterMenu = false;
            this.grvDetail.OptionsView.ShowGroupPanel = false;
            this.grvDetail.OptionsCustomization.AllowColumnMoving = false;
            this.grvDetail.OptionsCustomization.AllowGroup = false;
            this.grvDetail.OptionsMenu.EnableColumnMenu = false;
            this.grvDetail.OptionsMenu.EnableFooterMenu = false;
            this.grvDetail.OptionsNavigation.EnterMoveNextColumn = true;
            this.grvDetail.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;
            this.grvDetail.IndicatorWidth = Constants.INDICATOR_WIDTH;

            dteNgayThucHien.BackColor = REQUIRED_FIELD_COLOR;
            btneMaKy.BackColor = REQUIRED_FIELD_COLOR;

            txtColTonThucTe.Mask.MaskType = MaskType.Numeric;
            txtColTonThucTe.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            txtColTonThucTe.Mask.UseMaskAsDisplayFormat = true;

            txtColTonSS.Mask.MaskType = MaskType.Numeric;
            txtColTonSS.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            txtColTonSS.Mask.UseMaskAsDisplayFormat = true;

            txtChenhLech.Mask.MaskType = MaskType.Numeric;
            txtChenhLech.Mask.EditMask = ConfigurationConstant.NumericFormatString;
            txtChenhLech.Mask.UseMaskAsDisplayFormat = true;


        }
        #endregion

        #region override methods

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            if (this.CurrentBBKKEntry == null)
            {
                this.DoNew();
            }
        }

        protected override void BindingToControls(IBaseEntity entity)
        {
            base.BindingToControls(entity);

            this.bteMaBBKK.DataBindings.Clear();
            this.txtNguoiThucHien.DataBindings.Clear();
            this.dteNgayThucHien.DataBindings.Clear();
            this.txtThuKho.DataBindings.Clear();
            this.txtKeToan.DataBindings.Clear();
            this.txtGiamDoc.DataBindings.Clear();
            this.txtNguyenNhan.DataBindings.Clear();
            this.txtYKien.DataBindings.Clear();
            this.btneMaKy.DataBindings.Clear();

            this.bteMaBBKK.DataBindings.Add(BINDING_PROPERTY, entity, BienBanKiemKeKhoColumns.MaBBKKK.ToString());
            this.txtNguoiThucHien.DataBindings.Add(BINDING_PROPERTY, entity, BienBanKiemKeKhoColumns.NguoiThucHien.ToString());
            this.dteNgayThucHien.DataBindings.Add(BINDING_PROPERTY, entity, BienBanKiemKeKhoColumns.NgayThucHien.ToString());
            this.txtThuKho.DataBindings.Add(BINDING_PROPERTY, entity, BienBanKiemKeKhoColumns.ThuKho.ToString());
            this.txtKeToan.DataBindings.Add(BINDING_PROPERTY, entity, BienBanKiemKeKhoColumns.KeToan.ToString());
            this.txtGiamDoc.DataBindings.Add(BINDING_PROPERTY, entity, BienBanKiemKeKhoColumns.GiamDoc.ToString());
            this.txtNguyenNhan.DataBindings.Add(BINDING_PROPERTY, entity, BienBanKiemKeKhoColumns.NguyenNhan.ToString());
            this.txtYKien.DataBindings.Add(BINDING_PROPERTY, entity, BienBanKiemKeKhoColumns.YKien.ToString());
            this.btneMaKy.DataBindings.Add(BINDING_PROPERTY, entity, BienBanKiemKeKhoColumns.MaKy.ToString());

            

            BienBanKiemKeKho bbb = entity as BienBanKiemKeKho;

            SetValueCbbMonht(bbb.Thang);
            SetValueCbbYears(bbb.Nam);
            BindingToGrid();
            SetValueCbbKetluan(bbb.KetLuan);

        }

        public override void IsNewChanged()
        {
            if (IsNew)
            {
                LoadChiTietKKKhoForCreateNew(CurrentBBKKEntry.MaKy);
                CanPrint = false;
            }
            else
            {
                m_DetailItemsList.Clear();
                ChiTietBienBanKiemKeKhoBO chitietKKKservice = new ChiTietBienBanKiemKeKhoBO();
                m_DetailItemsList.AddRange(chitietKKKservice.GetAllChiTietBienBanKiemKeKhoByMaBBKK(CurrentBBKKEntry.MaBBKKK));
                CanPrint = true;
            }
        }
        protected override void FocusFirtsControl()
        {
            base.FocusFirtsControl();            
        }

        protected override void InitValidationRules()
        {
            base.InitValidationRules();
            Validator validate = new Validator(ValidationProvider);
            validate.AddValidationRule(base.CreateNotEmptyValidationRule());
            SetValidator(validate, dteNgayThucHien);

            validate = new Validator(ValidationProvider);
            validate.AddValidationRule(new DongMoKyValidateRules(true));
            SetValidator(validate, btneMaKy);

        }

        public override void New()
        {
            this.CurrentBBKKEntry = new Entity.BienBanKiemKeKho() 
            {
                NgayThucHien = Constants.BUSINESS_DATE,
                MaBBKKK = NEW_String,
                Thang = (byte)DateTime.Now.Month,
                Nam = DateTime.Now.Year
            };
            base.New();
        }

        protected override void ClearData()
        {
            New();
        }

        protected override bool Save()
        {
            try
            {
                ChiTietBienBanKiemKeKhos list = new ChiTietBienBanKiemKeKhos();
                list.AddRange(m_DetailItemsList);
                if (IsNew)
                {
                    CurrentBBKKEntry = Service.CreateBienBanKiemKeKho(CurrentBBKKEntry,list);
                }
                else
                {
                    Service.UpdateBienBanKiemKeKho(CurrentBBKKEntry,list);
                }
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }

        }

        protected override bool Delete()
        {
            try
            {
                Service.DeleteBienBanKiemKeKho(CurrentBBKKEntry);
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }

        protected override void Print()
        {
            try
            {
                BienBanKiemKeKhoViewer rpViewer = new BienBanKiemKeKhoViewer(CurrentBBKKEntry.MaBBKKK);
                rpViewer.StartPosition = FormStartPosition.CenterParent;
                rpViewer.WindowState = FormWindowState.Maximized;
                rpViewer.ShowDialog();
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        public override void Cancel()
        {
            //your code here
            base.Cancel();
        }

        protected override IBaseEntity GetEntity()
        {
            //need to get the latest record of the current Entity's ID or code then return it
            return base.GetEntity();
        }
        #endregion

        #region Lookups
        #endregion

        #region Form's function

        private void LoadChiTietKKKhoForCreateNew(string maky)
        {
            m_DetailItemsList.Clear();
            ChiTietBienBanKiemKeKhoBO chitietKKKservice = new ChiTietBienBanKiemKeKhoBO();
            m_DetailItemsList.AddRange(chitietKKKservice.GetAllChiTietBienBanKiemKeKhoByMaKy(maky));
        }

        private void BindingToGrid()
        {
            colSoPN.FieldName = ChiTietPhieuNhapColumns.SoPN.ToString();
            colMaThuoc.FieldName = LuuKhoColumns.MaThuoc.ToString();
            colHoatChat.FieldName = SanPhamColumns.TenHoatChat.ToString();
            colBietDuoc.FieldName = SanPhamColumns.TenBietDuoc.ToString();
            ColSoLo.FieldName = LuuKhoColumns.SoLo.ToString();
            colHanDung.FieldName = LuuKhoColumns.HanDung.ToString();
            colTonSoSach.FieldName = ChiTietBienBanKiemKeKhoColumns.TonSoSach.ToString();
            colTonThucTe.FieldName = ChiTietBienBanKiemKeKhoColumns.TonThucTe.ToString();
            colChenhLech.FieldName = ChiTietBienBanKiemKeKhoColumns.ChenhLechThucTe.ToString();
            colTinhTrang.FieldName = ChiTietBienBanKiemKeKhoColumns.TinhTrang.ToString();
            colHangSuDung.FieldName = LuuKhoColumns.HanSuDung.ToString();
            grdDetail.DataSource = m_DetailItemsList;
        }

        private void LoadObjectOnForm(string previousCode, string code, IBaseEntity ObjectLoad)
        {
            if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
            {
                if (IsNew)
                {
                    if (ObjectLoad != null)
                    {
                        if (IsDataChanged)
                        {
                            var result = ShowSaveConfimMessage();
                            if (result == DialogResult.Yes)
                            {
                                CurrentBBKKEntry.MaBBKKK = previousCode;
                                if (!base.ValidateControls() || !Save())
                                {
                                    return;
                                }
                            }
                        }
                        Entity = ObjectLoad;
                        IsNew = false;
                        IsDataChanged = false;
                    }
                    else
                    {
                        CurrentBBKKEntry.MaBBKKK = code;
                        Entity = CurrentBBKKEntry;
                        IsNew = true;//important
                        IsDataChanged = true;//important                        
                    }
                }
                else
                {
                    if (!IsDataChanged)
                    {
                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentBBKKEntry = new BienBanKiemKeKho();
                            CurrentBBKKEntry.MaBBKKK = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentBBKKEntry;
                            IsNew = true;//important
                            IsDataChanged = true;//important   
                        }
                    }
                    else
                    {
                        var result = ShowSaveConfimMessage();
                        if (result == DialogResult.Yes)
                        {
                            CurrentBBKKEntry.MaBBKKK = previousCode;
                            if (!base.ValidateControls() || !Save())
                            {
                                return;
                            }
                        }

                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentBBKKEntry = new BienBanKiemKeKho();
                            CurrentBBKKEntry.MaBBKKK = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentBBKKEntry; ;
                            IsNew = true;//important
                            IsDataChanged = true;//important 
                        }
                    }
                }
                ClearErrorMessage();
            }
        }

        private void LoadingProductToGrid(SanPham loadingProduct)
        {
            ChiTietBienBanKiemKeKho getRow = grvDetail.GetFocusedRow() as ChiTietBienBanKiemKeKho;
            bool isNewRow = false;
            if (getRow == null)
            {
                isNewRow = true;
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }
            else if (grvDetail.FocusedRowHandle < 0)
            {
                isNewRow = true;
                m_DetailItemsList.RemoveAt(m_DetailItemsList.Count - 1);
                m_DetailItemsList.RemoveRows.Remove(getRow);
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }

            ClearStatusMessage();
            grvDetail.ClearColumnErrors();

            getRow.MaThuoc = loadingProduct.MaThuoc;
            grvDetail.FocusedRowHandle = grvDetail.GetRowHandle(m_DetailItemsList.IndexOf(getRow));
            if (isNewRow == true)
            {
                getRow.CreatedDate = DateTime.Now;
                getRow.RowStatus = (byte)RowStatus.New;
            }
            grvDetail.RefreshEditor(true);
            grvDetail.FocusedColumn = grvDetail.VisibleColumns[0];
        }

        private void LoadingChiTietNhapToGrid(ChiTietPhieuNhap loadingProduct)
        {
            ChiTietBienBanKiemKeKho getRow = grvDetail.GetFocusedRow() as ChiTietBienBanKiemKeKho;
            bool isNewRow = false;
            if (getRow == null)
            {
                isNewRow = true;
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }
            else if (grvDetail.FocusedRowHandle < 0)
            {
                isNewRow = true;
                m_DetailItemsList.RemoveAt(m_DetailItemsList.Count - 1);
                m_DetailItemsList.RemoveRows.Remove(getRow);
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }

            ClearStatusMessage();
            grvDetail.ClearColumnErrors();

            getRow.MaThuoc = loadingProduct.MaThuoc;
            getRow.SoLo = loadingProduct.SoLo;
            getRow.MaLuuKho = loadingProduct.MaLuuKho;
            grvDetail.SetFocusedRowCellValue(colTonSoSach, 0);
            grvDetail.SetFocusedRowCellValue(colTonThucTe, 0);
            grvDetail.SetFocusedRowCellValue(colChenhLech, 0);
            grvDetail.FocusedRowHandle = grvDetail.GetRowHandle(m_DetailItemsList.IndexOf(getRow));
            if (isNewRow == true)
            {
                getRow.CreatedDate = DateTime.Now;
                getRow.RowStatus = (byte)RowStatus.New;
            }
            grvDetail.RefreshEditor(true);
            grvDetail.FocusedColumn = grvDetail.VisibleColumns[0];
        }

        //private void LoadDatasourceCbbThang()
        //{
        //    m_ListMonths = new List<ComboItem>();
        //    for (int i = 1; i <= 12; i++)
        //    {
        //        ComboItem item = new ComboItem();
        //        item.DisplayValue = i.ToString();
        //        item.ItemValue = i;
        //        m_ListMonths.Add(item);
                
        //    }
        //    cbbThang.Properties.Items.Clear();
        //    cbbThang.Properties.Items.AddRange(m_ListMonths);
        //}

        private void SetValueCbbYears(int year)
        {
            //cbbNam.SelectedItem = m_listYears.Find(o => o.ItemValue == year);
        }

        private void SetValueCbbMonht(byte month)
        {
            //cbbThang.SelectedItem = m_ListMonths.Find(o => o.ItemValue == month);
        }

        //private void LoadDatasourceCbbNam()
        //{
        //    m_listYears = new List<ComboItem>();
        //    for (int i = 1975; i < DateTime.Now.Year+10; i++)
        //    {
        //        ComboItem item = new ComboItem();
        //        item.DisplayValue = i.ToString();
        //        item.ItemValue = i;
        //        m_listYears.Add(item);
        //    }
        //    cbbNam.Properties.Items.Clear();
        //    cbbNam.Properties.Items.AddRange(m_listYears);
        //}

        private void LoadDatasourceCbbKetluan()
        {
            ArrayList tempItemList = BindDataUtil.BindDataCombobox("BBKKKKetluan", typeof(BBKKKKetluan));
            m_Ketluan = new List<ComboItem>();
            foreach (ComboItem item in tempItemList)
            {
                m_Ketluan.Add(item);
            }
            cbbKetLuan.Properties.Items.AddRange(m_Ketluan);
        }

        private void SetValueCbbKetluan(byte ketluan)
        {
            cbbKetLuan.SelectedItem = m_Ketluan.Find(o => o.ItemValue == ketluan);
        }

        #endregion

        private void bteMaBBKK_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                var form = new BienBanKiemKeKhoLookup();
                if (form.ShowDialog() == DialogResult.OK)
                {
                    IsNew = false;
                    if (form.BienBanKiemKeKhoSelected != null)
                    {
                        LoadObjectOnForm(bteMaBBKK.Text.Trim(), form.BienBanKiemKeKhoSelected.MaBBKKK, form.BienBanKiemKeKhoSelected);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteMaBBKK_Enter(object sender, EventArgs e)
        {
            if (bteMaBBKK.Text.Equals(NEW_String))
            {
                bteMaBBKK.Text = string.Empty;
            }
        }

        private void bteMaBBKK_Leave(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(bteMaBBKK.Text) && !IsNew)
                {
                    New();
                }
                else
                {
                    if (CurrentBBKKEntry == null) return;
                    string previousCode = DataConvertUltils.ToString(CurrentBBKKEntry.MaBBKKK);
                    string code = DataConvertUltils.ToString(bteMaBBKK.EditValue);
                    if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
                    {
                        BienBanKiemKeKho temPhieuXuat = Service.GetBienBanKiemKeKhoByID(code);
                        LoadObjectOnForm(previousCode, code, temPhieuXuat);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void grvDetail_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if ((e.Info.IsRowIndicator) && (e.RowHandle >= 0))
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void grvDetail_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (this.grvDetail.IsRowSelected(this.grvDetail.FocusedRowHandle) == true)
                {
                    ChiTietBienBanKiemKeKho row = (ChiTietBienBanKiemKeKho)this.grvDetail.GetRow(grvDetail.FocusedRowHandle);
                    int index = this.m_DetailItemsList.IndexOf(row);
                    if (index != -1)
                    {
                        bool isNewRow = (row.RowStatus == (byte)RowStatus.New);

                        this.m_DetailItemsList.RemoveAt(index);
                        if (isNewRow == true)
                        {
                            this.m_DetailItemsList.RemoveRows.Remove(row);
                        }
                        base.IsDataChanged = true;

                    }
                }
            }
          
        }

        private void grvDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
        }

        private void grvDetail_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        private void grvDetail_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (grvDetail.FocusedColumn != colTonThucTe&&grvDetail.FocusedColumn != colTinhTrang)
            {
                e.Cancel = true;
            }
        }

        private void grvDetail_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            
        }

        private void cbbThang_SelectedValueChanged(object sender, EventArgs e)
        {
            //CurrentBBKKEntry.Thang = (byte)((ComboItem)cbbThang.SelectedItem).ItemValue;
            //LoadChiTietKKkhoForCreateNew();
        }

        private void cbbNam_SelectedValueChanged(object sender, EventArgs e)
        {
            //CurrentBBKKEntry.Nam = (int)((ComboItem)cbbNam.SelectedItem).ItemValue;
            //LoadChiTietKKkhoForCreateNew();
        }

        private void cbbKetLuan_SelectedValueChanged(object sender, EventArgs e)
        {
            CurrentBBKKEntry.KetLuan = (byte)((ComboItem)cbbKetLuan.SelectedItem).ItemValue;
        }


        private void grvDetail_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {

            if (grvDetail.FocusedColumn == colTonThucTe)
            {
                int thucte = DataConvertUltils.ToInt(e.Value);
                if (thucte < 0)
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(INVALID_QUANTITY);
                }
            }
        }

        private void btneMaKy_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                DongMoKyLookup form = new DongMoKyLookup();
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.DongMoKySelected != null)
                    {
                        CurrentBBKKEntry.MaKy = DataConvertUltils.ToString(form.DongMoKySelected.MaKy);
                        CurrentBBKKEntry.Nam = form.DongMoKySelected.NgayMoKy.Year;
                        CurrentBBKKEntry.Thang = (byte)form.DongMoKySelected.NgayMoKy.Month;
                        LoadChiTietKKKhoForCreateNew(CurrentBBKKEntry.MaKy);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }
    }
}
